<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-form-item label="申请人">
                        <el-input v-model="searchForm.realName" placeholder="申请人" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="initTableData(1)">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <!-- 新增|刷新 -->
        <div class="flex items-center justify-between mb-4">
            <div>
                <el-button type="primary" size="small" @click="handleCreate">导入证书</el-button>
            </div>

            <el-tooltip effect="dark" content="刷新数据" placement="top">
                <el-button text @click="initTableData">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-tooltip>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
            <el-table-column label="操作类型" align="center">
                <template #default="{ row }">
                    {{ row.serialNo == null ? "后台导入" : "平台申请" }}
                </template>
            </el-table-column>

            <el-table-column label="申请人" align="center">
                <template #default="{ row }">
                    {{ row.applyUserName }}
                </template>
            </el-table-column>

            <el-table-column label="申请证书类型" align="center">
                <template #default="{ row }">
                    {{ row.templateType == 0 ? "工程师证书" : "公司证书" }}
                </template>
            </el-table-column>

            <el-table-column label="申请证书名称" align="center">
                <template #default="{ row }">
                    {{ row.certName }}
                </template>
            </el-table-column>

            <!-- <el-table-column label="支付状态" align="center">
                <template #default="{ row }">
                    {{ row.serialNo == null ? "-" : changePayState(row.payState) }}
                </template>
            </el-table-column> -->

            <!-- <el-table-column label="审批状态" align="center">
                <template #default="{ row }">
                    {{ row.serialNo == null ? "-" : changeState(row.auditState) }}
                </template>
            </el-table-column> -->

            <el-table-column label="审批时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.auditTime) }}
                </template>
            </el-table-column>

            <el-table-column label="驳回理由" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.auditRemark }}
                </template>
            </el-table-column>

            <el-table-column label="操作" width="240" align="center">
                <template #default="scope">
                    <div v-if="scope.row.serialNo == null">
                        <el-button type="primary" size="small" text
                            @click="downloadCert(scope.row.certUrl)">下载</el-button>

                        <el-popconfirm title="是否要删除该证书？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="deleteApply(scope.row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" text>删除</el-button>
                            </template>
                        </el-popconfirm>

                    </div>
                    <div v-else>
                        <el-button type="primary" size="small" text @click="showDetails(scope.row)">申请详情</el-button>
                        <el-button type="primary" size="small" text @click="auditDetails(scope.row)">审批详情</el-button>
                        <el-button v-if="
                            scope.row.auditState == 1 &&
                            scope.row.payState == 1
                        " type="primary" size="small" text @click="downloadCert(scope.row.certUrl)">下载</el-button>
                        <el-button v-else type="primary" size="small" text disabled>下载</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="initTableData" />
        </div>


        <!-- 新增|修改弹窗 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="140px" :inline="false">

                <el-form-item label="对应证书" prop="certId" style="margin-bottom: 20px">
                    <el-select v-model="form.certId" placeholder="对应证书">
                        <el-option v-for="item in certNameList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="证书持有者" prop="userId" style="margin-bottom: 20px">
                    <el-button @click="dialogTableVisible_user = true">
                        {{ checkedUser == null ? '选择证书持有者' : checkedUser.realName }}
                    </el-button>
                </el-form-item>

                <el-form-item label="证书有效开始时间" prop="validFromTime" style="margin-bottom: 20px">
                    <el-date-picker v-model="form.validFromTime" type="date" placeholder="证书有效开始时间" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="证书文件" prop="fileList">
                    <el-upload class="upload-demo" ref="upload" accept=".pdf" action="" :limit="1"
                        :on-change="fileChange" :file-list="form.fileList" :before-upload="beforeUpload"
                        :on-exceed="handleExceed" :http-request="uploadSubmit" :auto-upload="false">
                        <el-button size="small" type="primary">选取文件</el-button>
                        <div class="el-upload__tip" style="display: inline-block;margin-left: 20px">
                            请选择PDF证书文件
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
        </FormDrawer>
    </el-card>

    <!-- 申请详情 -->
    <SystemDialog title="申请详情" :visible="dialogTableVisible_apply" :height="50" :width="40" :showOkBtn="false"
        :showCloseBtn="true" @on-close="dialogTableVisible_apply = false"
        @on-confirm="dialogTableVisible_apply = false">
        <template v-slot:content>
            <div style="margin: 10px;padding: 10px;display: flex; justify-content: flex-start;">
                <!-- <span style="font-size: 15px">申请信息：</span> -->
                <el-form label-width="150px" :inline="false">
                    <el-form-item label="证书类型：">
                        <span>{{ formatTemplateType(detailForm.templateType) }}</span>
                    </el-form-item>
                    <el-form-item label="证书名称：">
                        <span>{{ detailForm.certName }}</span>
                    </el-form-item>
                    <el-form-item label="国籍：">
                        <span>{{ detailForm.nationality }}</span>
                    </el-form-item>

                    <el-form-item label="姓名：">
                        <span>{{ detailForm.realName }}</span>
                    </el-form-item>

                    <el-form-item label="电话：">
                        <span>{{ detailForm.phone }}</span>
                    </el-form-item>

                    <el-form-item label="邮箱：">
                        <span>{{ detailForm.email }}</span>
                    </el-form-item>

                    <el-form-item label="身份证：" v-if="detailForm.nationality == '中国'">
                        <span>{{ detailForm.idCard }}</span>
                    </el-form-item>

                    <el-form-item label="护照：" v-else>
                        <span>{{ detailForm.idCard }}</span>
                    </el-form-item>

                    <el-form-item v-if="detailForm.templateType == '0'" label="培训时间：">
                        <span>{{ dateFormatterMonth(detailForm.trainTime) }}</span>
                    </el-form-item>

                    <el-form-item v-if="detailForm.templateType == '0'" label="证件照：">
                        <el-image style="width: 100px; height: 100px" :src="detailForm.idPhoto"
                            :preview-src-list="detailForm.srcList">
                        </el-image>
                    </el-form-item>
                </el-form>
                <el-form label-width="150px" :inline="false">
                    <!-- <span style="font-size: 15px">公司信息：</span> -->
                    <el-form-item label="公司名称：">
                        <span>{{ detailForm.companyName }}</span>
                    </el-form-item>

                    <el-form-item label="公司地址：">
                        <span>{{ detailForm.companyAddress }}</span>
                    </el-form-item>

                    <el-form-item label="公司官网：">
                        <span>{{ detailForm.companyOfficialWebsite }}</span>
                    </el-form-item>

                    <el-form-item label="公司联系人：">
                        <span>{{ detailForm.companyManager }}</span>
                    </el-form-item>

                    <el-form-item label="公司联系人电话：">
                        <span>{{ detailForm.companyManagerPhone }}</span>
                    </el-form-item>

                    <el-form-item label="公司联系人邮箱：">
                        <span>{{ detailForm.companyManagerEmail }}</span>
                    </el-form-item>
                </el-form>
            </div>
        </template>
    </SystemDialog>

    <!-- 审批详情 -->
    <SystemDialog title="审批详情" :visible="approvalDetailDialogVisible" :height="50" :width="40" :showOkBtn="false"
        :showCloseBtn="true" @on-close="approvalDetailDialogVisible = false"
        @on-confirm="approvalDetailDialogVisible = false">
        <template v-slot:content>
            <el-form :model="approvalDetail" label-width="120px" :inline="false">
                <el-form-item label="申请人：">
                    <span>{{
                        approvalDetail.approvalRequestDto.applicantName
                        }}</span>
                </el-form-item>
                <el-form-item label="模板名称：">
                    <span>{{
                        approvalDetail.approvalTemplateDto.templateName
                        }}</span>
                </el-form-item>
                <el-form-item label="申请描述：">
                    <span>{{
                        approvalDetail.approvalRequestDto.description
                        }}</span>
                </el-form-item>
                <el-form-item label="审批状态：">
                    <span>{{
                        formatRequestStatus(
                            approvalDetail.approvalRequestDto.status
                        )
                    }}</span>
                </el-form-item>

                <el-steps :align-center="true">
                    <el-tooltip class="item" effect="dark" placement="top-start" v-for="(item, key) in steps" :key="key"
                        :content="item.tooltipInfo">
                        <el-step :title="item.title" :status="item.status">
                            <template #description>
                                <!-- 或签 -->
                                <div v-if="item.approvalType == 1">
                                    <span>{{ item.description }}</span>
                                </div>
                                <!-- 会签 -->
                                <div v-if="item.approvalType == 2" v-for="(desc, key) in item.description"
                                    :key="desc.key" style="font-size: 13px">
                                    <span>{{ desc.name }}</span><span>({{ desc.result }})</span><br /><span>{{ desc.time
                                        }}</span>
                                </div>
                            </template>
                        </el-step>
                    </el-tooltip>
                </el-steps>

                <el-form-item v-if="approvalDetail.approvalRequestDto.remark" label="拒绝原因：">
                    <span>{{ approvalDetail.approvalRequestDto.remark }}</span>
                </el-form-item>

                <el-form-item v-if="approvalDetail.approvalRequestDto.imageUrls != null" label="图片：">
                    <el-image style="width: 100px; height: 100px; margin-left: 5px"
                        v-for="item in approvalDetail.imagesDto" :key="item.url" :src="item.url"
                        :preview-src-list="item.srcList" fit="cover" />
                </el-form-item>
            </el-form>
        </template>
    </SystemDialog>

    <!-- 选择申请人弹窗 -->
    <SystemDialog title="选择申请人" :visible="dialogTableVisible_user" :height="60" :width="70"
        @on-close="dialogTableVisible_user = false" @on-confirm="dialogTableVisible_user = false">
        <template v-slot:content>
            <SelectUser v-if="dialogTableVisible_user" :showSelection="true" @getCheckedUser="getCheckedUser" />
        </template>
    </SystemDialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import SystemDialog from "~/components/SystemDialog.vue";
import FormDrawer from "~/components/FormDrawer.vue";
import { toast, toastWarn } from "~/composables/util";
import { dateFormatter, dateFormatterMonth } from "~/utils/common.js";
import SelectUser from "~/components/select-user.vue";
import { api_cert_list, api_cert_apply_enterCert, api_cert_apply_enterCert_delete } from "~/api/exam/certApi";
import { formatRequestStatus } from "~/api/approvalApi";

import {
    api_cert_apply_look_list,
    getRequestInfoByCertApplyId,
} from "~/api/exam/certApi";

// 表格分页数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const total = ref(0);
const limit = ref(10);

// 表单部分
// 是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改证书" : "导入证书")
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
    userId: null,
    certId: null,
    validFromTime: null,
    fileList: []
})
// 证书列表
const certNameList = ref(null)

//执行表单校验
const rules = {
    userId: [
        { required: true, message: '证书持有者不能为空', trigger: 'change' }
    ],
    certId: [
        { required: true, message: '对应证书不能为空', trigger: 'change' }
    ],
    validFromTime: [
        { required: true, message: '证书有效开始时间不能为空', trigger: 'change' }
    ],
    fileList: [
        { required: true, message: '证书文件不能为空', trigger: 'change' }
    ]
}

//选择证书持有人
const dialogTableVisible_user = ref(false)
const checkedUser = ref(null)
//获取选择的申请人
function getCheckedUser(data) {
    // console.log('checked user: ', JSON.stringify(data))
    if (data != null) {
        form.userId = data.id
        //显示内容
        checkedUser.value = data
        //如果有文件则清空为空校验
        if (formRef.value) {
            formRef.value.clearValidate(['userId'])
        }
    }
}

// 申请详情弹窗
const dialogTableVisible_apply = ref(false);

// 审批详情弹窗
const approvalDetailDialogVisible = ref(false);
// 审批详情
const approvalDetail = reactive({
    approvalTemplateDto: null,
    approvalRequestDto: null,
    imagesDto: null,
});

// steps
const steps = ref([]);

// 查询条件
const searchForm = reactive({
    auditState: "1",
    realName: null,
    page: currentPage.value,
    size: limit.value,
});

// 重置搜索框
const resetSearchForm = () => {
    searchForm.auditState = "1";
    searchForm.realName = null;
    initTableData(1);
};

// 详情form
const detailForm = ref(null);

// 生命周期函数
onMounted(() => {
    //初始化证书名称list
    initCertNameList()

    //初始化列表数据
    initTableData();
});

// 初始化证书名称list
function initCertNameList() {
    let paramIo = {}
    paramIo.state = 1
    paramIo.size = 1000
    api_cert_list(paramIo).then(res => {
        if (res && res.records) {
            certNameList.value = res.records
        } else {
            certNameList.value = null
        }
    })
}

// 获取数据
function initTableData(p = null) {
    //指定页码是否为空
    if (typeof p == "number") {
        currentPage.value = p;
    }

    loading.value = true;
    searchForm.page = currentPage.value;

    api_cert_apply_look_list(searchForm)
        .then((res) => {
            if (res) {
                tableData.value = res.records;
                total.value = Number(res.total);
            } else {
                tableData.value = [];
                total.value = 0;
            }
        })
        .finally(() => {
            loading.value = false;
        });
}

// 新增按钮点击事件
const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    checkedUser.value = null
    resetForm({
        userId: null,
        certId: null,
        validFromTime: null,
        fileList: []
    })
    //打开弹窗
    formDrawerRef.value.open()
};

// 展示详情
function showDetails(row) {
    detailForm.value = row;
    detailForm.value.srcList = [row.idPhoto];
    // console.log(JSON.stringify(detailForm.value))
    dialogTableVisible_apply.value = true;
}

// 审批详情
function auditDetails(row) {
    getRequestInfoByCertApplyId(row.id).then((res) => {
        approvalDetail.approvalTemplateDto = res.approvalTemplateDto;
        approvalDetail.approvalRequestDto = res.approvalRequestDto;
        let imageUrls = res.approvalRequestDto.imageUrls;
        if (null != imageUrls && imageUrls.length > 0) {
            let result = [];
            let imgs = imageUrls.split(",");
            let item = null;
            for (let i = 0; i < imgs.length; i++) {
                item = {};
                item.url = imgs[i];
                item.srcList = [imgs[i]];
                result.push(item);
            }
            approvalDetail.imagesDto = result;
        }

        //构建流程节点图
        let nodeList = res.approvalTemplateDto.nodeDtoList;
        steps.value = [];
        let defaultStep = {
            approvalType: 1,
            title: "提交申请",
            status: "success",
            tooltipInfo: "流程起点",
            description: dateFormatter(res.approvalRequestDto.createTime),
        };
        steps.value.push(defaultStep);
        let step = null;
        //会签描述信息
        let descList = [];
        //审核人list
        let nameList = [];
        //审核结果list
        let resultList = [];
        //审核时间list
        let resultDateList = [];
        //审核备注信息
        let commentsList = [];

        for (let i = 0; i < nodeList.length; i++) {
            //重置数据---------
            step = {};
            descList = [];
            nameList = [];
            resultList = [];
            resultDateList = [];
            commentsList = [];
            //重置数据---------

            //当前节点审批方式
            let approvalType = nodeList[i].approvalType;
            //获取审批人list
            let approvalRecordList = nodeList[i].approvalRecordDtos;
            for (let j = 0; j < approvalRecordList.length; j++) {
                nameList.push(approvalRecordList[j].approverName);
                resultList.push(approvalRecordList[j].approvalResult);
                resultDateList.push(
                    dateFormatter(approvalRecordList[j].approvalTime)
                );
                commentsList.push(approvalRecordList[j].comments);
                //会签特殊处理描述字段
                if (approvalType == 2) {
                    let desc = {};
                    desc.key = j;
                    desc.name = nameList[j];
                    desc.result = formatRecordResult(resultList[j]);
                    desc.time = resultDateList[j];
                    descList.push(desc);
                }
            }

            //提示信息
            step.tooltipInfo = "处理人: " + nameList.join("; ");

            //审批类型，1：或签，2：会签
            if (nodeList[i].approvalType == 1) {
                //审批类型
                step.approvalType = 1;

                //审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
                if (resultList.indexOf(0) !== -1) {
                    //标题
                    step.title = "未处理";
                    //节点描述
                    step.description = null;
                    //节点状态
                    step.status = "wait";
                    steps.value.push(step);
                } else if (resultList.indexOf(3) !== -1) {
                    //标题
                    step.title = "处理中";
                    //节点描述
                    step.description = null;
                    //节点状态
                    step.status = "process";
                    steps.value.push(step);
                } else if (resultList.indexOf(1) !== -1) {
                    let successIndex = resultList.indexOf(1);
                    //标题（此处是审核人）
                    step.title = nameList[successIndex];
                    //节点描述（此处是审核时间）
                    step.description = resultDateList[successIndex];
                    //节点状态；审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
                    step.status = "success";
                    steps.value.push(step);
                } else if (resultList.indexOf(2) !== -1) {
                    let errorIndex = resultList.indexOf(2);
                    //标题（此处是审核人）
                    step.title = nameList[errorIndex];
                    //节点描述（此处是审核时间）
                    step.description = resultDateList[errorIndex];
                    //节点状态；审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
                    step.status = "error";
                    //如果是拒绝显示原因
                    approvalDetail.approvalRequestDto.remark =
                        commentsList[errorIndex];

                    steps.value.push(step);
                }
            } else if (nodeList[i].approvalType == 2) {
                //审批类型
                step.approvalType = 2;

                //审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
                if (resultList.indexOf(0) !== -1) {
                    //标题
                    step.title = "未处理";
                    //节点描述
                    step.description = null;
                    //节点状态
                    step.status = "wait";
                    steps.value.push(step);
                } else {
                    //标题
                    step.title = null;
                    //节点状态
                    if (resultList.indexOf(2) !== -1) {
                        step.status = "error";
                        //如果是拒绝显示原因
                        approvalDetail.approvalRequestDto.remark =
                            commentsList[resultList.indexOf(2)];
                    } else if (resultList.indexOf(3) !== -1) {
                        step.status = "process";
                    } else {
                        step.status = "success";
                    }
                    step.description = descList;
                    steps.value.push(step);
                }
            }
        }

        //申请人名称
        approvalDetail.approvalRequestDto.applicantName = row.applyUserName;

        approvalDetailDialogVisible.value = true;
    });
}

// 下载证书
function downloadCert(url) {
    window.location.href = url;
}

// 状态转换
function changeState(val) {
    if (val == 0) {
        return "未审批";
    } else if (val == 1) {
        return "已通过";
    }
    return "未通过";
}

// 状态转换
function changePayState(val) {
    if (val == null || val == 3) {
        return "未支付";
    } else if (val == 1) {
        return "已支付";
    }
    return "支付异常";
}

// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

//提交表单
const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return
        //触发文件上传
        upload.value.submit();
    })
}


// 上传组件 -------------------------------------------
const upload = ref(null)

// 文件改变
const fileChange = (file, fileList) => {
    //console.log("fileChange =================" + JSON.stringify(file))
    //console.log("fileList =================" + JSON.stringify(fileList))
    form.fileList = fileList;
    //如果有文件则清空为空校验
    if (formRef.value) {
        formRef.value.clearValidate(['fileList'])
    }
}

// 文件超出个数限制
const handleExceed = (file, fileList) => {
    toastWarn('只能选择一个文件');
}

// 上传前 文件校验
const beforeUpload = (file) => {
    //console.log("==============" + JSON.stringify(file))
    const isLt2M = file.size / 1024 / 1024 < 30
    if (!isLt2M) {
        toastWarn('上传文件大小不能超过 30MB!')
        return false;
    }
    return true;
}

//提交上的文件
const uploadSubmit = (param) => {

    let fileObj = param.file// 相当于input里取得的files
    let paramIo = new FormData()// FormData 对象
    paramIo.append('files', fileObj)// 文件对象
    paramIo.append('userId', form.userId)
    paramIo.append('certId', form.certId)
    paramIo.append('validFromTime', new Date(form.validFromTime))
    //loading
    formDrawerRef.value.showLoading()
    const fun = api_cert_apply_enterCert(paramIo)
    fun.then(res => {
        toast(drawerTitle.value + "成功")
        //清空file文件
        upload.value.clearFiles();
        //修改刷新当前页，新增刷新第一页
        initTableData(editId.value ? false : 1)
        formDrawerRef.value.close()
    })
        .finally(() => {
            //close loading
            formDrawerRef.value.hideLoading()
        })
}
// 上传组件 -------------------------------------------


// 删除项目
function deleteApply(id) {
    api_cert_apply_enterCert_delete(id).then(res => {
        toast("删除成功")
        initTableData()
    })
}

const formatTemplateType = (type) => {
    if (type == '0') {
        return "工程师证书"
    } else if (type == '1') {
        return "公司证书"
    } else if (type == '2') {
        return "船员证书"
    } else {
        return "未知"
    }
}
</script>

<style scoped>
.hide ::v-deep .el-upload--picture-card {
    display: none;
}

.el-form-item {
    margin-bottom: 10px;
}

::v-deep .el-form-item__content {
    white-space: normal;
    /* 允许内容换行 */
    word-break: break-all;
    /* 在长单词或 URL 地址内部进行换行 */
}
</style>